<template>
    <div class="crm-crmRental-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:rental:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.rentalName" placeholder="请输入租借方名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractName" placeholder="请输入联系人姓名" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.expiryStatus" placeholder="请选择到期状态" multiple clearable class="w100">
                        <el-option label="未到期" value="0"></el-option>
                        <el-option label="即将到期" value="1"></el-option>
                        <el-option label="已到期" value="2"></el-option>
                        <el-option label="已续期" value="3"></el-option>
                        <el-option label="已结束" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="签约时间" value="rentalStartTime"></el-option>
                        <el-option label="到期时间" value="rentalEndTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item v-if="search.more" label="到期天数范围">
                    <el-input-number v-model="search.expiryMinDay" placeholder="Min天数"></el-input-number>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input-number v-model="search.expiryMaxDay" placeholder="Max天数"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:rental:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmRental()">新增</el-button>
            <el-button v-auth="'crm:rental:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmRental()" :disabled="tableData.selections.length != 1">修改</el-button>
            <el-button v-auth="'crm:rental:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableCrmRentalRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column label="租借方名称" prop="rentalName" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="联系人姓名" prop="contractName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="手机号码" prop="contractMobile" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="省份" prop="areaName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="租借开始时间" prop="rentalStartTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="租借结束时间" prop="rentalEndTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="人才名称" prop="talenterName" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="租借金额" prop="rentalAmount" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.rentalAmount == '0'" class="color-primary">免费</span>
                        <span v-else class="color-primary">{{scope.row.rentalAmount}}元/{{ scope.row.rentalUnit == 'H' ? '小时' : scope.row.rentalUnit == 'D' ? '天' : scope.row.rentalUnit == 'M' ? '月' : scope.row.rentalUnit == 'Y' ? '年' : ''}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="到期状态" prop="expiryStatus" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.expiryStatus == '0'" class="color-primary">未到期</span>
                        <span v-else-if="scope.row.expiryStatus == '1'" class="color-warning">即将到期</span>
                        <span v-else-if="scope.row.expiryStatus == '2'" class="color-danger">已到期</span>
                        <span v-else-if="scope.row.expiryStatus == '3'" class="color-success">已续期</span>
                        <span v-else-if="scope.row.expiryStatus == '4'" class="color-info">已结束</span>
                    </template>
                </el-table-column>
                <el-table-column label="到期天数" prop="expiryDay" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.expiryDay == -99999"></span>
                        <span v-else-if="scope.row.expiryDay >= 0">还有 {{ scope.row.expiryDay }} 天到期</span>
                        <span v-else-if="scope.row.expiryDay < 0" class="color-danger">已到期 {{ -scope.row.expiryDay }} 天，请及时续期</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="250" v-auths="['crm:rental:info', 'crm:rental:edit', 'crm:rental:remove', 'crm:rental:renewal', 'crm:rental:finished']">
                    <template #default="scope">
                        <el-button v-auth="'crm:rental:info'" type="primary" link @click="onOpenInfoCrmRental(scope.row)">详情</el-button>
                        <el-button v-auth="'crm:rental:edit'" type="primary" link @click="onOpenEditCrmRental(scope.row, 'edit')">修改</el-button>
                        <el-button v-auth="'crm:rental:remove'" type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                        <el-button v-auth="'crm:rental:renewal'" v-show="!['4'].includes(scope.row.expiryStatus)" type="primary" link @click="onOpenEditCrmRental(scope.row, 'renewal')">续期</el-button>
                        <el-button v-auth="'crm:rental:finished'" v-show="!['4'].includes(scope.row.expiryStatus)" type="primary" link @click="onOpenFinishedCrmRental(scope.row)">终止</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmRental ref="addCrmRentalRef" @submit="onTableSearch"/>
        <EditCrmRental ref="editCrmRentalRef" @submit="onTableSearch"/>
        <InfoCrmRental ref="infoCrmRentalRef"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddCrmRental from '/@/views/crm/rental/addCrmRental.vue';
import EditCrmRental from '/@/views/crm/rental/editCrmRental.vue';
import InfoCrmRental from '/@/views/crm/rental/infoCrmRental.vue';
import { getCrmRentalList, delCrmRental, finishedCrmRental } from '/@/api/crm/rental/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/rental',
    components: { AddCrmRental, EditCrmRental, InfoCrmRental },
    setup() {
        const tableCrmRentalRef = ref();
        const addCrmRentalRef = ref();
        const editCrmRentalRef = ref();
        const infoCrmRentalRef = ref();
        const state = reactive({
            search:{
                rentalName: undefined,
                contractName: undefined,
                expiryStatus: [],
                expiryMinDay: undefined,
                expiryMaxDay: undefined,
                timefield: 'createTime',
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false
            }
        });

        const loadTableData = (params) => {
            const search = { ...state.search, ...params };
            const expiryStatusStr = search.expiryStatus.join(',');
            getCrmRentalList({
                ...search,
                expiryStatus: expiryStatusStr,
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmRentalRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.rentalName = undefined;
            state.search.contractName = undefined;
            state.search.expiryStatus = [];
            state.search.expiryMinDay = undefined;
            state.search.expiryMaxDay = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        const onOpenInfoCrmRental = (row: object) => {
            infoCrmRentalRef.value.openDialog(row);
        };
        // 打开新增弹窗
        const onOpenAddCrmRental = (row?: object) => {
            addCrmRentalRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmRental = (row?: object, operate?: string) => {
            row = row || state.tableData.selections[0];
            row.operate = operate || 'edit';
            editCrmRentalRef.value.openDialog(row);
        };
        const onOpenFinishedCrmRental = (row: object) => {
            ElMessageBox.confirm(`确认【终止】租借操作吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                finishedCrmRental([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('操作成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的租借信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmRental(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条租借信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmRental([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };
        // 页面加载时
        onMounted(() => {
            loadTableData({});
        });
        return {
            tableCrmRentalRef,
            addCrmRentalRef,
            editCrmRentalRef,
            infoCrmRentalRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenInfoCrmRental,
            onOpenAddCrmRental,
            onOpenEditCrmRental,
            onOpenFinishedCrmRental,
            onTabelRowsDel,
            onTabelRowDel,
            ...toRefs(state),
        };
    },
};
</script>